package kcp

import (
	"net"

	"github.com/xtaci/kcp-go/v5"

	"gitee.com/hasika/common-server/conn/impl_base"
	"gitee.com/hasika/common-server/conn/inet"
	"gitee.com/hasika/common-server/option"
)

type Listener struct {
	net.Listener
	option *option.KcpOption
}

func NewKcpListener(address string, serviceOption *option.ServiceOption) (*Listener, error) {
	ln, err := impl_base.ListenWithRetry(func(address string) (net.Listener, error) {
		ln, err := kcp.Listen(address)
		if err != nil {
			return nil, err
		}
		return ln, nil
	}, address, serviceOption.ListenRetryOption())
	if err != nil {
		return nil, err
	}
	ls := &Listener{Listener: ln, option: serviceOption.KcpOption()}
	return ls, nil
}

func (t *Listener) Accept() (inet.Conn, error) {
	cn, err := t.Listener.Accept()
	if err != nil {
		return nil, err
	}
	conn := NewKcpConnection(cn.(*kcp.UDPSession), t.option)
	return conn, nil
}

func (t *Listener) Close() {
	t.Listener.Close()
	inet.Log.Infof("kcp listener stopped")
}
